package com.kelvin.oocl;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import com.kelvin.oocl.constart.SystemConstant;
import com.kelvin.oocl.controller.DiapatcherImpl;
import com.kelvin.oocl.controller.Dispatcher;

public class App {
    public static void main( String[] args ) {
    	String filePath = "./src/main/java/customer.txt";
    	Dispatcher dispatcher = new DiapatcherImpl();
    	BufferedReader reader =null;
    	BufferedOutputStream out = null;
    	ServerSocket server =null;
    	try {
    		dispatcher.initDBData(new File(filePath));
			server = new ServerSocket(8888);
			Socket socket = server.accept();
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new BufferedOutputStream(socket.getOutputStream());
			out.write(SystemConstant.TIP_MSG.getBytes());
			while(true){
				out.write("Please input->\r\n".getBytes());
				out.flush();
				String line = reader.readLine();
				String result = dispatcher.dispatcher(line.trim());
				if(SystemConstant.QUIT.equals(result)){
					break;
				}
				out.write(result.getBytes());
				out.flush();
			}
		} catch (IOException e) {
			try {
				out.write("An Exception is appreaing!".getBytes());
				out.flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}finally {
			try {
				if(reader!=null){
					reader.close();
				}
				if(out!=null){
					out.close();
				}if(server!=null){
					server.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
}
